package com.hopu.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hopu.domain.Menu;
import com.hopu.domain.Role;
import com.hopu.domain.UserRole;
import com.hopu.result.PageEntity;
import com.hopu.result.ResponseEntity;
import com.hopu.service.IRoleMenuService;
import com.hopu.service.IRoleService;
import com.hopu.service.IUserRoleService;
import com.hopu.utils.UUIDUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import static com.hopu.result.ResponseEntity.error;
import static com.hopu.result.ResponseEntity.success;


@Controller
@RequestMapping("/role")
public class RoleController {
    @Autowired
    private IRoleService roleService;
    @Autowired
    private IRoleMenuService roleMenuService;
    @Autowired
    private IUserRoleService userRoleService;

    //    向用户列表页面跳转
    @GetMapping("/toRolePage")
    public String roleList() {
        return "admin/role/role_list";
    }

    /**
     * 多条件分页查询用户列表信息，根据用户名username、电话tel、邮箱email模糊查询
     */
    @RequestMapping("/list")
    @ResponseBody
    @RequiresPermissions("role:list")
    public IPage<Role> findByPage(@RequestParam(value = "page", defaultValue = "1") int page,
                                  @RequestParam(value = "limit", defaultValue = "5") int limit,
                                  Role role) {
        Page<Role> page2 = new Page<Role>(page, limit);
        QueryWrapper<Role> queryWrapper = new QueryWrapper<>(new Role());
        if (role != null) {
            if (!StringUtils.isEmpty(role.getRole())) {
                queryWrapper.like("role", role.getRole());
            }
            if (!StringUtils.isEmpty(role.getRemark())) {
                queryWrapper.like("remark", role.getRemark());
            }
        }
        IPage<Role> roleIPage = roleService.page(page2, queryWrapper);
        return roleIPage;
    }
//    @RequestMapping("/list")
//    @ResponseBody
//    @RequiresPermissions("role:list")
//    public PageEntity list(@RequestParam(value = "page",defaultValue = "1") Integer pageNum,
//                           @RequestParam(value = "limit",defaultValue = "3") Integer pageSize,
//                           Role role){
//        // 设置分页
//        Page<Role> page = new Page<>(pageNum,pageSize);
//        // 封装查询条件
//        QueryWrapper<Role> queryWrapper = new QueryWrapper<>(new Role());
//        if(role !=null && StringUtils.isNotEmpty(role.getRole())){
//            queryWrapper.like("role",role.getRole());
//        }
//
//        IPage<Role> iPage = roleService.page(page,queryWrapper);
//        return new PageEntity(iPage);
//    }

    // 向角色添加页面跳转
    @RequestMapping("/toRoleAdd")
    public String toAddPage(){
        return "admin/role/role_add";
    }
    /**
     * 添加
     */
    @RequestMapping("/addRole")
    @ResponseBody
    public ResponseEntity addRole(Role role) {
        Role role2 = roleService.getOne(new QueryWrapper<Role>().eq("role", role.getRole()));
        if (role2!=null) {
            return error("角色名已存在");
        }
        role.setId(UUIDUtils.getID());
        role.setCreateTime(new Date());
        roleService.save(role);
        return success();
    }

    //    到更新用户信息页面
    @RequestMapping("/toRoleUpdate")
    public String toUpdatePage(String id, Model model){
        Role role = roleService.getById(id);
        model.addAttribute("role", role);
        return "admin/role/role_update";
    }
    /**
     * 更新
     */
    @RequestMapping("/updateRole")
    @ResponseBody
    public ResponseEntity updateRole(Role role) {
        role.setUpdateTime(new Date());
        roleService.updateById(role);
        return success();
    }

    /**
     * 删除（支持批量删除）
     */

    @RequestMapping("/delete")
    @ResponseBody
    public ResponseEntity delete(@RequestBody ArrayList<Role> roles) throws Exception {
        try {
            List<String> list = new ArrayList<String>();
            for (Role role : roles) {
                if ("root".equals(role.getRole())) {
                    throw new Exception("root账号不能被删除");
                }
                list.add(role.getId());
            }
            roleService.removeByIds(list);
        } catch (Exception e) {
            e.printStackTrace();
            return error(e.getMessage());
        }
        return success();
    }

    /***
     * 跳转分配权限页面
     */
    @RequestMapping("/toSetMenuRole")
    public String toSetMenuRole(@RequestParam(value = "id") String roleId, HttpServletRequest request) {
        request.setAttribute("roleId",roleId);
        return "admin/role/role_setMenu";
    }

    /**
     * 权限设置
     */
    @ResponseBody
    @RequestMapping("/setMenu")
    public ResponseEntity setMenu(String roleId, @RequestBody List<Menu> menus) {
        roleService.setMenu(roleId, menus);
        return success();
    }

    /**
     * 查询用户关联的角色列表
     */
    @ResponseBody
    @RequestMapping("/roleList")
    public PageEntity list(String userId){
        // 先查询指定用户已经有哪些角色
        List<UserRole> userRoleList = userRoleService.list(new QueryWrapper<UserRole>().eq("user_id", userId));

        // 查询所有角色信息
        List<Role> list = roleService.list();

        // 判断用户哪些角色已经绑定，添加LAY_CHECKED字段为true
//        list.forEach(role -> {
//            List<String> roleIds = userRoleList.stream().map(userRole -> userRole.getRoleId()).collect(Collectors.toList());
//            if(roleIds.contains(role.getId())){
//                role.setLAY_CHECKED(true);
//            }
//        });
        ArrayList<JSONObject> jsonObjects = new ArrayList<>();
        list.forEach(role -> {
            // 先需要把对象转换为JSON格式
            JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(role));
            // 判断是否已经有了对应的权限
            List<String> roleIds = userRoleList.stream().map(userRole -> userRole.getRoleId()).collect(Collectors.toList());
            if(roleIds.contains(role.getId())){
                jsonObject.put("LAY_CHECKED",true);
            }
            jsonObjects.add(jsonObject);
        });

        return new PageEntity(jsonObjects.size(),jsonObjects);
//        return new PageEntity(list.size(),list);
    }


}
